#include "preHeader.h"
#include "SpellMgr.h"

SpellMgr::SpellMgr()
{
}

SpellMgr::~SpellMgr()
{
}

bool SpellMgr::LoadSpellRelation()
{
	auto pSITbl = sDBMgr.GetTable<SpellInfo>();
	auto pSLITbl = sDBMgr.GetTable<SpellLevelInfo>();
	auto pSLEITbl = sDBMgr.GetTable<SpellLevelEffectInfo>();
	for (auto itr = pSITbl->Begin(); itr != pSITbl->End(); ++itr) {
		auto& siInfo = itr->second;
		SpellPrototype siPt;
		siPt.siInfo = &siInfo;
		m_spellList.emplace(siInfo.spellID, siPt);
	}
	for (auto itr = pSLITbl->Begin(); itr != pSLITbl->End(); ++itr) {
		auto& sliInfo = itr->second;
		auto siItr = m_spellList.find(sliInfo.spellID);
		if (siItr == m_spellList.end()) {
			continue;
		}
		auto& sliList = siItr->second.sliList;
		SpellLevelPrototype sliPt;
		sliPt.sliInfo = &sliInfo;
		sliList.push_back(sliPt);
	}
	for (auto itr = pSLEITbl->Begin(); itr != pSLEITbl->End(); ++itr) {
		auto& sleiInfo = itr->second;
		auto siItr = m_spellList.find(sleiInfo.spellID);
		if (siItr == m_spellList.end()) {
			continue;
		}
		auto& sliList = siItr->second.sliList;
		auto sliItr = std::find_if(std::begin(sliList), std::end(sliList),
			[&sleiInfo](const SpellLevelPrototype& sliPt) {
			return sliPt.sliInfo->spellLevelID == sleiInfo.spellLevelID;
		});
		if (sliItr == sliList.end()) {
			continue;
		}
		auto& sleiList = sliItr->sleiList;
		SpellLevelEffectPrototype sleiPt;
		sleiPt.sleiInfo = &sleiInfo;
		sleiList.push_back(sleiPt);
	}
	for (auto& pair : m_spellList) {
		auto& sliList = pair.second.sliList;
		std::sort(sliList.begin(), sliList.end(),
			[](PutTwoRArgs(SpellLevelPrototype, sliPt)) {
			return sliPt1.sliInfo->spellLevelID <
				sliPt2.sliInfo->spellLevelID;
		});
		for (auto& sliPt : sliList) {
			auto& sleiList = sliPt.sleiList;
			std::sort(sleiList.begin(), sleiList.end(),
				[](PutTwoRArgs(SpellLevelEffectPrototype, sleiPt)) {
				return sleiPt1.sleiInfo->spellLevelEffectID <
					sleiPt2.sleiInfo->spellLevelEffectID;
			});
		}
	}
	return true;
}

const SpellPrototype* SpellMgr::GetSpellPrototype(uint32 spellID) const
{
	auto itr = m_spellList.find(spellID);
	return itr != m_spellList.end() ? &itr->second : NULL;
}
